<?php

/**
* @Author:  	Daniel Dinh
* @Email:   	webdevelopmentvn@gmail.com
* @Link: 		http://www.joomsoft.net
* @Version: 	1.0
* @copyright:	Joomsoft.net
* @license:		Commercial
*/


defined('_JEXEC') or die;

class JSNPluginHelper
{

	public static function addSubmenu($vName)
	{
		JSubMenuHelper::addEntry(
			JText::_('COM_JSNPLUGIN_SUBMENU_JSNPLUGIN'),
			'index.php?option=com_jsnplugin&view=jsnplugin',
			$vName == 'jsnplugin'
		);
	
		JSubMenuHelper::addEntry(
			JText::_("COM_JSNPLUGIN_SUBMENU_PLUGINS"),
			"index.php?option=com_jsnplugin&view=plugins",
			$vName == "plugins"
		);
		JSubMenuHelper::addEntry(
			JText::_("COM_JSNPLUGIN_SUBMENU_GROUPS"),
			"index.php?option=com_jsnplugin&view=groups",
			$vName == "groups"
		);
		JSubMenuHelper::addEntry(
			JText::_("COM_JSNPLUGIN_SUBMENU_EVENTS"),
			"index.php?option=com_jsnplugin&view=events",
			$vName == "events"
		);
		JSubMenuHelper::addEntry(
			JText::_("COM_JSNPLUGIN_SUBMENU_JSNFIELDS"),
			"index.php?option=com_jsnplugin&view=jsnfields",
			$vName == "jsnfields"
		);
	}
	/**
	 * Gets a list of the actions that can be performed.
	 * @return	JObject
	 * @since	1.6
	 */

	public static function getActions()
	{
		$user	= JFactory::getUser();
		$result	= new JObject;
		$assetName = 'com_jsnplugin';
		$actions = array(
			'core.admin', 'core.manage', 'core.create', 'core.edit', 'core.edit.state', 'core.delete'
		);
		foreach ($actions as $action) {
			$result->set($action,	$user->authorise($action, $assetName));

		}
		return $result;

	}
	function quickIconButton( $link, $image, $text ) {
		
		$lang	= &JFactory::getLanguage();
		$button = '';
		$button .= '<div class="icon-wrapper">';
		$button .=	'<div class="icon">'
				   .'<a href="'.$link.'">'
				   .JHTML::_('image', 'administrator/components/com_jsnplugin/assets/images/'.$image, $text )
				   .'<span>'.$text.'</span></a>'
				   .'</div>';
		$button .= '</div>';
		return $button;
	}

	function getFieldSetting($fieldname,$obj)
	{
		$path = JPATH_COMPONENT.DS.'libs'.DS.'fields'.DS;
		$field = simplexml_load_file($path.$fieldname);
		$fieldObj = array();
		$objvalue = json_decode($obj->data);
		if($field)
		{
			foreach($field as $key=>$prop)
			{
				$newattr = array();
				foreach($prop->attributes() as $key1=>$attr)
				{
					$newattr[$key1] = (string)$attr;
				}
				$fieldObj[$key]  = JSNPluginHelper::createFieldElement($key,$newattr,$objvalue->$key);
			}
		}
		return $fieldObj;
	}
	function createFieldElement($key,$el,$val)
	{
		$sel = $val ? $val : $el['value'];
		switch($el['element'])
		{
			case 'text':
				$element = '<input type="text" name="fopt['.$key.']" value="'.$sel.'" class="'.$el['class'].'"  size="'.$el['size'].'"/>';
			break;
			case 'boolean':
				$options = array();
				$options[] = array('value'=>0,'text'=>JText::_("JNO"));
				$options[] = array('value'=>1,'text'=>JText::_("JYES"));
				$element = JHTML::_("select.genericlist",$options,'fopt['.$key.']',$el['class'],'value','text',$sel);
			break;
			case 'filter':
				$options = array();
				$options[] = array('value'=>'html','text'=>JText::_("HTML"));
				$options[] = array('value'=>'raw','text'=>JText::_("Raw"));
				$element = JHTML::_("select.genericlist",$options,'fopt['.$key.']',$el['class'],'value','text',$sel);
			break;
			case 'textarea':
				$element = '<textarea name="fopt['.$key.']"  class="'.$el['class'].'"   cols="'.$el['cols'].'"  rows="'.$el['rows'].'"/>'.$sel.'</textarea>';
			break;
		}
		return $element;
	}
	public function getFieldLanguages($pid)
	{
		// get data
		$db = & JFactory::getDBO();
		$db->setQuery("select p.*, g.title as groupname from #__jsnp_plugin p INNER JOIN #__jsnp_group g ON p.id_group = g.id WHERE p.id=$pid");
		$plug = $db->loadObject();

		$db->setQuery("select f.*, fd.data from #__jsnp_jsnfield f LEFT JOIN #__jsnp_field_data fd ON f.id= fd.id_field WHERE f.published=1 AND f.id_plugin=$pid ORDER BY f.ordering");
		$fields = $db->loadObjectList();
		// define plugin name
		$plugin_name = "plg_".strtolower($plug->groupname)."_".strtolower($plug->title);
		$languages = @explode(",",$plug->language);
		$datalang = array();
		foreach($languages as $lang)
		{
			$langstr= strtoupper('PLG_'.$plug->groupname.'_'.$plug->title) . ' = "'. $plug->label .'"' .chr(10);
			foreach($fields as $field)
			{
				$field_data = json_decode($field->data);
				$langstr.= strtoupper("PLG_".$plug->groupname."_".$plug->title."_".$field->title).' = "'.$field_data->label.'"'.chr(10);
			}
			$langstr.=strtoupper('PLG_'.$plug->title.'_XML_DESCRIPTION') . ' = "'.$plug->description .'"';
			$datalang[$lang] = $langstr;
		}
		return $datalang;
	}
	
	public function getXMLInstall($version)
	{
		$path = JPATH_COMPONENT.DS.'libs'.DS.'xml'.DS;
		$filename= $path."joomla$version.xml";
		$handle = fopen($filename, "r");
		$contents = fread($handle, filesize($filename));
		fclose($handle);
		return $contents;
	}
	public function getPluginName($plugin)
	{
		return strtolower(trim($plugin->title));	
	}
	public function createPluginFolder($plugin,$languages,$events,$fields)
	{
		$path = JPATH_COMPONENT.DS.'export'.DS;
		$plugin_name = 	strtolower(trim($plugin->title));
		//@unlink($path.$plugin_name);
		if(file_exists($path.$plugin_name))
			@mkdir($path.$plugin_name,0777);
		@copy($path.'index.html',$path.$plugin_name.DS.'index.html');
		@mkdir($path.$plugin_name.DS.'language',0777);
		@copy($path.'index.html',$path.$plugin_name.DS.'language'.DS.'index.html');
		@mkdir($path.$plugin_name.DS.'assets',0777);
		@copy($path.'index.html',$path.$plugin_name.DS.'assets'.DS.'index.html');
		@mkdir($path.$plugin_name.DS.'assets'.DS.'css',0777);
		@copy($path.'index.html',$path.$plugin_name.DS.'assets'.DS.'css'.DS.'index.html');
		//write css content
		$cpath = $path.$plugin_name.DS;
		$csshandler = fopen($path.$plugin_name.DS.'assets'.DS.'css'.DS.'style.css',"w+");
		fwrite($csshandler,$plugin->css);
		fclose($csshandler);
		@mkdir($path.$plugin_name.DS.'assets'.DS.'images',0777);
		@copy($path.'index.html',$path.$plugin_name.DS.'assets'.DS.'images'.DS.'index.html');
		@mkdir($path.$plugin_name.DS.'assets'.DS.'js',0777);
		@copy($path.'index.html',$path.$plugin_name.DS.'assets'.DS.'js'.DS.'index.html');
		
		//write javascript content
		$jshandler = fopen($path.$plugin_name.DS.'assets'.DS.'js'.DS.'script.js',"w+");
		fwrite($jshandler,$plugin->javascript);
		fclose($jshandler);
			
		//make languages
		$lpath = $path.$plugin_name.DS.'language'.DS;
		$install_langs = '';
		foreach($languages as $lang)
		{
			// ini
			$lfile = $lang->language.strtolower('.plg_'.$plugin->groupname.'_'.$plugin_name.'.ini');	
			$handler = fopen($lpath.$lfile,"w+");
			fwrite($handler,$lang->data);
			fclose($handler);
			$install_langs .=chr(9).chr(9).'<language tag="'.$lang->language.'">language/'.$lfile.'</language>'.chr(10);
			//ini sys
			$lfile = $lang->language.strtolower('.plg_'.$plugin->groupname.'_'.$plugin_name.'.sys.ini');	
			$handler = fopen($lpath.$lfile,"w+");
			fwrite($handler,$lang->data);
			fclose($handler);
			$install_langs .=chr(9).chr(9).'<language tag="'.$lang->language.'">language/'.$lfile.'</language>'.chr(10);
		}
		//make php file
		$phptext = '<?php'.chr(10);
		$phptext.='/**'.chr(10);		
		$phptext.='*@copyright	'.$plugin->copyright.chr(10);		
		$phptext.='*@license	'.$plugin->license.chr(10);		
		$phptext.='*@author	'.$plugin->author.chr(10);		
		$phptext.='*@authorEmail	'.$plugin->author_email.chr(10);		
		$phptext.='*@authorURL	'.$plugin->author_url.chr(10);		
		$phptext.='*/'.chr(10);
		$phptext.='class plg'.ucfirst($plugin->groupname).ucfirst($plugin->title).' extends JPlugin'.chr(10);		
		$phptext.='{'.chr(10);		
		$phptext.=''.chr(10);		
		$phptext.=''.chr(10);		
		foreach($events as $event)
			$phptext.= $event->data.chr(10);
		$phptext.=''.chr(10);		
		$phptext.='}'.chr(10);		
		
		$phpfile = strtolower($plugin->title).'.php';
		$phandler = fopen($cpath.$phpfile,"w+");
		fwrite($phandler,$phptext);
		fclose($phandler);
		// make install xml file
		$plugin_install_name = "plg_".strtolower($plugin->groupname)."_".strtolower($plugin->title);
		//author
		$xmlcontent = JSNPluginHelper::getXMLInstall($plugin->jversion);
		$xmlcontent = str_replace("{groupname}",$plugin->groupname,$xmlcontent);
		$plug_author = '<name>'.$plugin_install_name.'</name>'.chr(10);
		$plug_author .= chr(9).'<author>'.$plugin->author.'</author>'.chr(10);
		$plug_author .= chr(9).'<creationDate>'.date('d-m-Y').'</creationDate>'.chr(10);
		$plug_author .= chr(9).'<copyright>'.$plugin->copyright.'</copyright>'.chr(10);
		$plug_author .= chr(9).'<license>'.$plugin->license.'</license>'.chr(10);
		$plug_author .= chr(9).'<authorEmail>'.$plugin->author_email.'</authorEmail>'.chr(10);
		$plug_author .= chr(9).'<authorUrl>'.$plugin->author_url.'</authorUrl>'.chr(10);
		$plug_author .= chr(9).'<version>'.$plugin->version.'</version>'.chr(10);
		$plug_author .= chr(9).'<description>'.strtoupper('PLG_'.$plugin->title.'_XML_DESCRIPTION').'</description>'.chr(10);
		//install file
		$plug_files  = '<files>'.chr(10);
		$plug_files .= chr(9).chr(9).'<filename  plugin="'.strtolower($plugin->title).'">'.strtolower($plugin->title).'.php</filename>'.chr(10);
		$plug_files .= chr(9).chr(9).'<filename>index.html</filename>'.chr(10);
		$plug_files .= chr(9).chr(9).'<folder>assets</folder>'.chr(10);
		$plug_files .= chr(9).chr(9).'<folder>language</folder>'.chr(10);
		$plug_files .= chr(9).'</files>'.chr(10);
		//install language
		$plug_langs = '<languages>'.chr(10);
		$plug_langs.= $install_langs.chr(10);
		$plug_langs.= chr(9).'</languages>'.chr(10);
		//params
		
		$xmlcontent = str_replace("{author}",$plug_author,$xmlcontent);
		$xmlcontent = str_replace("{files}",$plug_files,$xmlcontent);
		$xmlcontent = str_replace("{language}",$plug_langs,$xmlcontent);
		$xmlcontent = str_replace("{params}",$fields,$xmlcontent);
		//export
		//echo  $xmlcontent;exit;
		$xmlfile = strtolower($plugin->title.'.xml');
		$xhandler = fopen($path.strtolower($plugin->title).DS.$xmlfile,"w+");
		fwrite($xhandler,$xmlcontent);
		fclose($xhandler);
		
		$source = $path.$plugin_name.DS;
		$destination = $path.$plugin_name.'.zip';
		JSNPluginHelper::makePackage($source,$destination);
		JSNPluginHelper::download($plugin_name.'.zip',$path);
	}
	function makePackage($source, $destination)
	{
		if (!extension_loaded('zip') || !file_exists($source)) {
			return false;
		}
		if(is_file($destination))
			unlink($destination);
		$zip = new ZipArchive();

		if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {

			return false;
		}
	

		$source = str_replace('\\', '/', realpath($source));
	
		if (is_dir($source) === true)
		{
			$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
	
			foreach ($files as $file)
			{
				$file = str_replace('\\', '/', realpath($file));
	
				if (is_dir($file) === true)
				{
					$zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
				}
				else if (is_file($file) === true)
				{
					$zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
				}
			}
		}
		else if (is_file($source) === true)
		{
			$zip->addFromString(basename($source), file_get_contents($source));
		}
	
		return $zip->close();
	}


	public function download($filename, $path)
	{
		
		while (@ob_end_clean());
		if( $isLink ){
			header( "Location: " . substr( $filename , 6 ) );
			return;
		}	
		$fsize = @filesize($path.$filename);
		//$mod_date = date('r', filemtime( $path.$filename ) );
		$cont_dis = 'attachment';
		// required for IE, otherwise Content-disposition is ignored
		if(ini_get('zlib.output_compression'))  {
	
			ini_set('zlib.output_compression', 'Off');
		}
		//ob_start();
		header("Pragma: public");
		header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
		header("Expires: 0");
		header("Content-Transfer-Encoding: binary");
		header( 'Content-Disposition:' . $cont_dis .';'
			.' filename="' . $filename . '";'
			//. ' modification-date="' . $mod_date . '";'
			. ' size=' . $fsize .';'	
			); //RFC2183
		header("Content-Type: "    . $mime );			// MIME type
		header("Content-Length: "  . $fsize);
		if( ! ini_get('safe_mode') ) { // set_time_limit doesn't work in safe mode
			@set_time_limit(0);
		}
		// No encoding - we aren't using compression... (RFC1945)
		//header("Content-Encoding: none");
		//header("Vary: none");
		JSNPluginHelper::readfile_chunked($path.$filename);
	
	}
	public function readfile_chunked($filename,$retbytes=true)
    {
   		$chunksize = 1*(1024*1024); // how many bytes per chunk
   		$buffer = '';
   		$cnt =0;
   		$handle = fopen($filename, 'rb');
   		if ($handle === false) {
       		return false;
   		}

   		while (!feof($handle)) {
       		$buffer = fread($handle, $chunksize);
       		echo $buffer;
			@ob_flush();
			flush();
       		if ($retbytes) {
           		$cnt += strlen($buffer);
       		}
   		}

       $status = fclose($handle);
   	   if ($retbytes && $status) {
       		return $cnt; // return num. bytes delivered like readfile() does.
   		}
   		return $status;
	} // end function download file 
	
}

